package jp.co.sharp.android.parents.kidsguard.activity.common;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.PowerSettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.MimamoriConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.MimamoriPhoneDlg;
import jp.co.sharp.android.parents.kidsguard.common.OpenBluetoothConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessPointDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.MessageConstants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestCodeConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothItemDto;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;
import jp.co.sharp.android.parents.kidsguard.utils.CommonUtils;

public class MimamoriBusinessService {

    // 0: 初期化 1: onServiceDiscoveryChanged
    private int mBluetoothFlag = 0;
    // みまもり 開始する
    private final static int MIMAMORI_OPEN = 0;
    // みまもり 終了
    private final static int MIMAMORI_CLOSE = 1;
    // みまもり チェック SIM
    private final static int MIMAMORI_CHECK_SIM = 2;
    // みまもり チェック 連絡先
    private final static int MIMAMORI_CHECK_CONTACTS = 3;
    // OPEN みまもり
    private static final int OPEN_MIMAMORI_CONNECTION_BLUETOOTH = 8;
    // Open みまもり Error
    private static final int OPEN_MIMAMORI_ERROR = 9;
    // Open みまもり Success
    private static final int OPEN_MIMAMORI_SUCCESS = 10;
    // Close みまもり Success
    private static final int CLOSE_MIMAMORI_SUCCESS = 11;
    private static final int DISCONNECTION_BLUETOOTH = 6;
    private static final int CONNECTION_BLUETOOTH_FAILED = 7;

    // ページオブジェクト
    private Context mContext;
    private ParentBleTransfer mParentBleTransfer;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private App mApp;

    // Mimamori 再接続使用するには
    private BluetoothItemDto mBluetoothItemDto;
    // 接続機器情報
    private KidInfoEntity mKidInfoEntity;
    private boolean mOpenMimamoriWarn = false;
    private int mBluetoothConnection = 0;
    private boolean mKidReceiveFlag = false;
    private NotificationManager mNotificationManager;
    private Intent mIntent;

    private static final String TAG = "TAG";
    /**
     * みまもり初期化
     * @param pContext ページオブジェクト
     * @param pApp
     */
    public MimamoriBusinessService(Context pContext, App pApp, Intent pIntent, NotificationManager pNotificationManager) {
        this.mContext = pContext;
        this.mParentBleTransfer = pApp.getmParentBleTransfer();
        this.mApp = pApp;
        this.mNotificationManager = pNotificationManager;
        this.mIntent = pIntent;
    }

    /**
     * 連絡先の追加を待っています
     * @param pOpenMimamoriWarn
     */
    public void onContactAddResult(boolean pOpenMimamoriWarn) {
        mOpenMimamoriWarn = pOpenMimamoriWarn;
        mimamoriProcess(MIMAMORI_OPEN);
    }

    /**
     * ブロードキャストを登録する
     */
    public void registerReceiver() {
        initReceiver();
    }

    /**
     * ラジオをオフにする
     */
    public void unRegisterReceiver() {
        mContext.unregisterReceiver(receiver);
        mContext.unregisterReceiver(mimamoriReceiver);
    }

    /**
     * ラジオをオフにする
     */
    public void unRegisterSystemReceiver() {
        mContext.unregisterReceiver(systemReceiver);
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                    // ブロードキャストの再登録
                    mContext.unregisterReceiver(systemReceiver);
                    initReceiver();
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // Bluetoothステータス監視
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_CONNECTION) {
                        mBluetoothFlag = Constants.STATUS_BLUETOOTH_CONNECTION;
                    } else if (bluetoothReceiverDto.getStatus() == Constants.STATUS_BLUETOOTH_DISCONNECTION &&
                            bluetoothReceiverDto.getReson() == Constants.REASON_BLUETOOTH_USER_DISCONNECTION) {
                        // Mimamori 起こるかもしれない
                        Message msg = new Message();
                        msg.what = DISCONNECTION_BLUETOOTH;
                        msg.obj = macAddress;
                        handler.sendMessage(msg);
                    }
                } else if (Intent.ACTION_NEW_OUTGOING_CALL.equals(action)) {

                } else {
                    TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
                    telephonyManager.listen(new PhoneStateListener(){
                        @Override
                        public void onCallStateChanged(int state, String incomingNumber) {
                            super.onCallStateChanged(state, incomingNumber);
                            /*Intent freshIntent = new Intent();*/
                            switch(state){
                                case TelephonyManager.CALL_STATE_IDLE:
//                                    CommonUtils.stopRingtone(null, null);
//                                    CommonUtils.stopVibrator(null);
//                    freshIntent.setAction("com.android.music.musicservicecommand.pause");
//                    freshIntent.putExtra("command", "pause");
//                    mContext.sendBroadcast(freshIntent);
                                    break;
                                case TelephonyManager.CALL_STATE_OFFHOOK:
                                    CommonUtils.stopRingtone(null, null);
                                    CommonUtils.stopVibrator(null);
                                    break;
                                case TelephonyManager.CALL_STATE_RINGING:
                                    CommonUtils.stopRingtone(null, null);
                                    CommonUtils.stopVibrator(null);
//                    freshIntent.setAction("com.android.music.musicservicecommand.pause");
//                    freshIntent.putExtra("command", "pause");
//                    mContext.sendBroadcast(freshIntent);
                                    break;
                            }
                        }
                    }, PhoneStateListener.LISTEN_CALL_STATE);
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };
    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        // ロック画面
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 画面を開く
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        // 電話ダイヤルブロックの登録
        filter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);

        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_SEARCH);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_SERVICE_DISCOVERY_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        mContext.registerReceiver(receiver, filter);
        mContext.registerReceiver(mimamoriReceiver, filter);
        mContext.registerReceiver(systemReceiver, filter);
    }

    /**
     * デバイス 接続
     * @param pConnectionFlag  OPEN みまもり設定
     */
    private void connectDevice(int pConnectionFlag) {

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter) {
            if (!bluetoothAdapter.isEnabled()) {
                // Bluetoothがオンになっていない
                OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(mContext, R.style.commonDlg);
                openBluetoothConfirmDlg.show();
                openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        openBluetoothConfirmDlg.dismiss();
                        mContext.startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                    }
                });
            } else {
                this.mBluetoothConnection = pConnectionFlag;
                // 接続開始
                String pDlgMsg = "接続中...";
                mDealWithWaitingDlg = new DealWithWaitingDlg(mContext, R.style.dealWithWaitingDlg, pDlgMsg, false);
                mDealWithWaitingDlg.show();
                new ConnectBluetoothThread().start();
            }
        }
    }

    /**
     * 接続Thread
     */
    private class ConnectBluetoothThread extends Thread {
        @Override
        public void run() {
            try {
                mBluetoothItemDto = new BluetoothItemDto();
                synchronized (mBluetoothItemDto) {
                    mParentBleTransfer.enableScanLeDevice(true);
                    while (null == mBluetoothItemDto.getMacId()) {
                        mBluetoothItemDto.wait(7000L);
                        mParentBleTransfer.enableScanLeDevice(false);
                        if (mBluetoothItemDto.getMacId() == null) {
                            Message msg = new Message();
                            msg.what = CONNECTION_BLUETOOTH_FAILED;
                            handler.sendMessage(msg);
                        }
                        break;
                    }
                    if (null != mBluetoothItemDto.getMacId()) {
                        connectBluetooth(mBluetoothItemDto);
                        mBluetoothItemDto.wait(3000L);
                        if (!Constants.DEVICE_CONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
                            Message msg = new Message();
                            msg.what = CONNECTION_BLUETOOTH_FAILED;
                            handler.sendMessage(msg);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 接続
     * @param pBluetoothItemDto
     */
    private void connectBluetooth(BluetoothItemDto pBluetoothItemDto) {
        this.mParentBleTransfer.connectLeDevice(pBluetoothItemDto.getMacAddress());
    }

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_SEARCH.equals(action)) {
                    // 从intent中获取设备
                    BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String deviceName = device.getName();
                    String macAddress = device.getAddress();
                    byte[] scanRecord = (byte[]) intent.getByteArrayExtra(RequestReceiverConstants.RECEIVER_MAC_ID_KEY);
                    String scanRecordString = new String(scanRecord).trim();
                    String macId = scanRecordString.substring(scanRecordString.length() - 6, scanRecordString.length());

                    if (null != mKidInfoEntity && macId.equals(mKidInfoEntity.getMacId())) {
                        synchronized (mBluetoothItemDto) {
                            mBluetoothItemDto.setMacId(macId);
                            mBluetoothItemDto.setMacAddress(macAddress);
                            mBluetoothItemDto.setBluetoothName(deviceName);
                            mBluetoothItemDto.notify();
                        }
                    }

                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_SERVICE_DISCOVERY_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (mBluetoothFlag == Constants.STATUS_BLUETOOTH_CONNECTION && bluetoothReceiverDto.isDiscoveryState()) {
                        Message msg = new Message();
                        msg.what = mBluetoothConnection;
                        handler.sendMessage(msg);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (0 == msg.what) {
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
            } else if (DISCONNECTION_BLUETOOTH == msg.what) {
                //
                KidInfoEntity kidInfoEntity = mApp.findKidInfoByMacAddress((String) msg.obj);
                if (null != kidInfoEntity) {
                    kidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                    mApp.updateKidInfo(kidInfoEntity);
                }
                // TODO Mimamori
                if (null != kidInfoEntity && kidInfoEntity.getControlled()) {
                    mApp.addmLsIsMimamori((String) msg.obj);
                    isMimamoriChance();
                }

            } else if (OPEN_MIMAMORI_CONNECTION_BLUETOOTH == msg.what) {
                // Open みまもり設定
                mKidInfoEntity.setMacAddress(mBluetoothItemDto.getMacAddress());
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_CONNECTION_SUCCESS);
                mApp.updateKidInfo(mKidInfoEntity);
                mDealWithWaitingDlg.dismiss();
                mimamoriProcess(MIMAMORI_OPEN);

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            }
        }
    };

    /**
     * Mimamori
     * @param pMimamoriStep 0:みまもり 開始する 1:みまもり 終了
     */
    private void mimamoriProcess(int pMimamoriStep) {
        Log.i(TAG, "HomeActivity_mimamoriProcess");
        // 開く
        if(pMimamoriStep == MIMAMORI_OPEN) {
            // 接続バテン
            if (Constants.DEVICE_DISCONNECTION_FAILED.equals(mKidInfoEntity.getBtConnStatus())
                    || Constants.DEVICE_DISCONNECTION_SUCCESS.equals(mKidInfoEntity.getBtConnStatus())) {
                connectDevice(OPEN_MIMAMORI_CONNECTION_BLUETOOTH);
                return;
            }

            if (mKidInfoEntity.getNeverShow() || mOpenMimamoriWarn) {
                mOpenMimamoriWarn = false;
                String pDlgMsg = "起動中...";
                mDealWithWaitingDlg = new DealWithWaitingDlg(mContext, R.style.dealWithWaitingDlg, pDlgMsg, false);
                mDealWithWaitingDlg.show();
                new MimamoriThread(MIMAMORI_CHECK_CONTACTS).start();
            } else {
                ProcessPointDlg processPointDlg = new ProcessPointDlg(mContext, R.style.commonDlg, MessageConstants.MSG_MIMAMORI);
                processPointDlg.show();
                processPointDlg.setOnOperateSetListener(new ProcessPointDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet(boolean cbViewDlg) {
                        if (cbViewDlg) {
                            mKidInfoEntity.setNeverShow(true);
                            mApp.updateKidInfo(mKidInfoEntity);
                        }
                        processPointDlg.dismiss();

                        String pDlgMsg = "起動中...";
                        mDealWithWaitingDlg = new DealWithWaitingDlg(mContext, R.style.dealWithWaitingDlg, pDlgMsg, false);
                        mDealWithWaitingDlg.show();
                        new MimamoriThread(MIMAMORI_CHECK_CONTACTS).start();;
                    }
                });
            }
            // 閉じる
        } else if (pMimamoriStep == MIMAMORI_CLOSE) {
            new MimamoriThread(MIMAMORI_CLOSE).start();
        }
    }

    /**
     * Mimamori 設定　自分の電話番号チェック
     */
    private void mimamoriPhoneNumCheck() {
        Log.i(TAG, "HomeActivity_mimamoriPhoneNumCheck");
        if (null == mKidInfoEntity.getParentTel() || "".equals(mKidInfoEntity.getParentTel())) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            }
            ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(mContext, R.style.commonDlg, MessageConstants.MSG_CHECK_PHONE_NUM_NONE);
            processWarningDlg.show();
            processWarningDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarningDlg.dismiss();
                }
            });
        } else {
            new MimamoriThread(MIMAMORI_OPEN).start();;
        }
    }

    /**
     * Mimamori Thread
     */
    private class MimamoriThread extends Thread {
        private int mMimamoriStep;
        public MimamoriThread(int pMimamoriStep) {
            this.mMimamoriStep = pMimamoriStep;
        }

        @Override
        public void run() {
            switch (mMimamoriStep) {
                case MIMAMORI_OPEN:
                    try {
                        mBluetoothItemDto = new BluetoothItemDto();
                        synchronized (mBluetoothItemDto) {
                            openMimamori();
                            while (!mBluetoothItemDto.isMimamoriState()) {
                                mBluetoothItemDto.wait(10000L);
                                if (!mBluetoothItemDto.isMimamoriState()) {
                                    Message msg = new Message();
                                    msg.what = OPEN_MIMAMORI_ERROR;
                                    mimamoriHandler.sendMessage(msg);
                                }
                                break;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case MIMAMORI_CLOSE:
                    closeMimamori();
                    break;
                case MIMAMORI_CHECK_SIM:
                    kidSimCardCheck();
                    break;
                case MIMAMORI_CHECK_CONTACTS:
                    kidContactsCheck();
                    break;
            }
        }
    }

    /**
     * Mimamori キッズケータイの電話番号チェック
     */
    private void kidSimCardCheck() {
        Log.i(TAG, "HomeActivity_kidSimCardCheck");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_ISDOCOMO_SIM_CARD_INSERT);
            jsonObject.put("data", JSONObject.NULL);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Mimamori お使いのスマートフォンの電話番号がキッズケータイに登録されていません。
     */
    private void kidContactsCheck() {
        Log.i(TAG, "HomeActivity_kidContactsCheck");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_CONTACTS);
            jsonObject.put("data", JSONObject.NULL);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * Mimamori 開く
     */
    private void openMimamori() {
        Log.i(TAG, "HomeActivity_openMimamori");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_MIMAMORI_STATE);
            JSONObject jsonData = new JSONObject();
            jsonData.put("state", 0);
            jsonData.put("phone", mKidInfoEntity.getParentTel());
            jsonObject.put("data", jsonData);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Mimamori 閉じる
     */
    private void closeMimamori() {
        Log.i(TAG, "HomeActivity_closeMimamori");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_MIMAMORI_STATE);
            JSONObject jsonData = new JSONObject();
            jsonData.put("state", 1);
            jsonData.put("phone", mKidInfoEntity.getParentTel());
            jsonObject.put("data", jsonData);

            this.mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver mimamoriReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {
                        mKidReceiveFlag = true;
                    }
                } else if (mKidReceiveFlag && RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);
                    if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getString("result").equals(Constants.ON_SYNC_RESULT)) {
                            Message msg = new Message();
                            msg.what = CLOSE_MIMAMORI_SUCCESS;
                            mimamoriHandler.sendMessage(msg);
                        }
                    } else  if (RequestMethodConstants.METHOD_ON_GET_KID_PHONE.equals(jsonObject.getString("method"))) {
                        JSONObject jsonData = jsonObject.getJSONObject("data");
                        mBluetoothItemDto.setMimamoriState(true);
                        mBluetoothItemDto.setKidPhone(jsonData.getString("phone"));

                        Message msg = new Message();
                        msg.what = OPEN_MIMAMORI_SUCCESS;
                        mimamoriHandler.sendMessage(msg);
                    } else if (RequestMethodConstants.METHOD_GET_CONTACTS.equals(jsonObject.getString("method"))) {
                        if (jsonObject.isNull("data")) {
                            Message msg = new Message();
                            msg.what = MIMAMORI_CHECK_CONTACTS;
                            mimamoriHandler.sendMessage(msg);
                        } else {
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            if (null != jsonArray && jsonArray.length() > 0) {
                                boolean exist = false;
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonItem = jsonArray.getJSONObject(i);
                                    if (null != mKidInfoEntity.getParentTel() &&
                                            jsonItem.getString("phone").equals(mKidInfoEntity.getParentTel())) {
                                        exist = true;
                                        break;
                                    }
                                }
                                if (!exist) {
                                    Message msg = new Message();
                                    msg.what = MIMAMORI_CHECK_CONTACTS;
                                    mimamoriHandler.sendMessage(msg);
                                } else {
                                    new MimamoriThread(MIMAMORI_CHECK_SIM).start();
                                }
                            } else {
                                Message msg = new Message();
                                msg.what = MIMAMORI_CHECK_CONTACTS;
                                mimamoriHandler.sendMessage(msg);
                            }
                        }
                    } else if (RequestMethodConstants.METHOD_ISDOCOMO_SIM_CARD_INSERT.equals(jsonObject.getString("method"))) {
                        JSONObject jsonData = jsonObject.getJSONObject("data");
                        if (jsonData.getInt("state") == 0) {
                            mimamoriPhoneNumCheck();
                        } else {
                            Message msg = new Message();
                            msg.what = MIMAMORI_CHECK_SIM;
                            mimamoriHandler.sendMessage(msg);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Handler mimamoriHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (OPEN_MIMAMORI_ERROR == msg.what) {
                // Open みまもり Error
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(mContext, R.style.commonDlg, MessageConstants.MSG_MIMAMORI_OPEN_ERROR);
                processWarringDlg.show();
                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        processWarringDlg.dismiss();
                    }
                });
            } else if (OPEN_MIMAMORI_SUCCESS == msg.what) {
                // Open みまもり Success
                mKidInfoEntity.setControlled(true);
                mKidInfoEntity.setKidTel(mBluetoothItemDto.getKidPhone());
                mApp.updateKidInfo(mKidInfoEntity);
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }

                // ウェイクの処理
                synchronized (mBluetoothItemDto) {
                    mBluetoothItemDto.notify();
                }
            } else if (MIMAMORI_CHECK_SIM == msg.what) {
                // Open みまもり Error
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }

                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(mContext, R.style.commonDlg, MessageConstants.MSG_CHECK_SIM_CARD_ERROR);
                processWarringDlg.show();
                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        processWarringDlg.dismiss();
                    }
                });
            } else if (MIMAMORI_CHECK_CONTACTS == msg.what) {
                // Open みまもり Error
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
                Intent intent = new Intent();
                MimamoriConfirmDlg mimamoriConfirmDlg = new MimamoriConfirmDlg(
                        mContext,
                        R.style.commonDlg,
                        MessageConstants.MSG_CHECK_CONTACTS_ERROR,
                        MessageConstants.MSG_CHECK_CONTACTS_ERROR_CONFIRM,
                        MessageConstants.MSG_CHECK_CONTACTS_ERROR_CANCEL,
                        null);
                mimamoriConfirmDlg.show();
                mimamoriConfirmDlg.setOnConfirmSetListener(new MimamoriConfirmDlg.OnConfirmSetListener() {
                    @Override
                    public void onOperateSet(String pMacId) {
                        mimamoriConfirmDlg.dismiss();
                        intent.setClass(mContext, MimamoriContactAddActivity.class);
                        ((Activity)mContext).startActivityForResult(intent, RequestCodeConstants.MIMAMORI_CONTACT_ADD);
                    }
                });
                mimamoriConfirmDlg.setOnCancelSetListener(new MimamoriConfirmDlg.OnCancelSetListener() {
                    @Override
                    public void onOperateSet(String pMacId) {
                        mimamoriConfirmDlg.dismiss();
                    }
                });
            }
        }
    };

    /**
     * Mimamori 起こる
     */
    private void isMimamoriChance() {
        Log.i(TAG, "HomeA");
        List<String> lsIsMimamori = mApp.getmLsIsMimamori();
        if (lsIsMimamori.isEmpty()) {
            return;
        }
        // Mimamori Kid
        String isMimamoriAdr = lsIsMimamori.get(lsIsMimamori.size() - 1);
        Iterator<String> iterator = lsIsMimamori.iterator();
        while(iterator.hasNext()){
            String item = (String)iterator.next();
            if(isMimamoriAdr.equals(item)){
                iterator.remove();
            }
        }
        // 最初に選択したデバイスをキャンセルする
        KidInfoEntity oldKidInfoEntity = mApp.findKidInfoBySelect();
        oldKidInfoEntity.setSelected(false);
        mApp.updateKidInfo(oldKidInfoEntity);
        // 新しく選択したデバイスを設定します
        KidInfoEntity kidInfoEntity = mApp.findKidInfoByMacAddress(isMimamoriAdr);
        kidInfoEntity.setSelected(true);
        mApp.updateKidInfo(kidInfoEntity);
        //
        mKidInfoEntity = kidInfoEntity;

        // 通知音
        if (kidInfoEntity.getRingToneSwitch()) {
            CommonUtils.playRingtone(mContext, kidInfoEntity.getRingToneUrl());
        }
        // バイブレーション
        if (kidInfoEntity.getShockSwitch()) {
            CommonUtils.playVibrator(mContext);
        }

        // 緊急ポップアップ通知
        if (mApp.getAppStatus() != Constants.APP_STATUS_INIT) {
            int channelId = mApp.findKidInfoPosition(kidInfoEntity);
            mNotificationManager.cancel(channelId);
            PendingIntent pendingIntent = PendingIntent.getActivity(mContext,0, mIntent,0);
            if(Build.VERSION.SDK_INT >= 26)
            {
                //当sdk版本大于26
                String description = "ParentApp";
                int importance = NotificationManager.IMPORTANCE_HIGH;
                NotificationChannel channel = new NotificationChannel(String.valueOf(channelId), description, importance);
                mNotificationManager.createNotificationChannel(channel);
                Notification notification = new Notification.Builder(mContext, String.valueOf(channelId))
                        .setCategory(Notification.CATEGORY_MESSAGE)
                        .setSmallIcon(R.mipmap.parent_app_icon)
                        .setContentText(MessageFormat.format("{0}とはぐれました。至急確認してください！", kidInfoEntity.getKidName()))
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setFullScreenIntent(pendingIntent,true)
                        .setVisibility(Notification.VISIBILITY_PUBLIC)
                        .build();
                mNotificationManager.notify(channelId, notification);
            }
            else
            {
                //当sdk版本小于26
                Notification notification = new NotificationCompat.Builder(mContext)
                        .setContentText(MessageFormat.format("{0}とはぐれました。至急確認してください！", kidInfoEntity.getKidName()))
                        .setContentIntent(pendingIntent)
                        .setSmallIcon(R.mipmap.parent_app_icon)
                        .setAutoCancel(true)
                        .setFullScreenIntent(pendingIntent,true)
                        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                        .build();
                mNotificationManager.notify(channelId, notification);
            }
        }

        // 第三
        MimamoriConfirmDlg mimamoriConfirmDlg = new MimamoriConfirmDlg(
                mContext,
                R.style.commonDlg,
                MessageFormat.format(MessageConstants.MSG_MIMAMORI_WARN_3, mKidInfoEntity.getKidName()),
                MessageConstants.MSG_MIMAMORI_WARN_3_CONFIRM,
                MessageConstants.MSG_MIMAMORI_WARN_3_CANCEL,
                mKidInfoEntity.getMacId());
        mimamoriConfirmDlg.show();
        mimamoriConfirmDlg.setOnConfirmSetListener(new MimamoriConfirmDlg.OnConfirmSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriConfirmDlg.dismiss();
                // 継続
                connectDevice(OPEN_MIMAMORI_CONNECTION_BLUETOOTH);
            }
        });
        mimamoriConfirmDlg.setOnCancelSetListener(new MimamoriConfirmDlg.OnCancelSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriConfirmDlg.dismiss();
                mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                mKidInfoEntity.setControlled(false);
                mApp.updateKidInfo(mKidInfoEntity);
            }
        });

        // 第二
        MimamoriPhoneDlg mimamoriPhoneDlg = new MimamoriPhoneDlg(mContext,
                R.style.commonDlg,
                MessageFormat.format(MessageConstants.MSG_MIMAMORI_WARN_2, mKidInfoEntity.getKidName()),
                MessageConstants.MSG_MIMAMORI_WARN_2_CONFIRM,
                MessageConstants.MSG_MIMAMORI_WARN_2_CANCEL,
                mKidInfoEntity.getMacId());
        mimamoriPhoneDlg.show();
        mimamoriPhoneDlg.setOnConfirmSetListener(new MimamoriPhoneDlg.OnConfirmSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriPhoneDlg.dismiss();
                KidInfoEntity kidInfoItem = mApp.findKidInfoByMacId(pMacId);
                // キッズケータイがかける電話番号
                Intent dialIntent =  new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + kidInfoItem.getKidTel()));
                mContext.startActivity(dialIntent);
            }
        });
        mimamoriPhoneDlg.setOnCancelSetListener(new MimamoriPhoneDlg.OnCancelSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriPhoneDlg.dismiss();
                KidInfoEntity kidInfoItem = mApp.findKidInfoByMacId(pMacId);
                // 通知音
                if (kidInfoItem.getRingToneSwitch()) {
                    CommonUtils.stopRingtone(mContext, kidInfoItem.getRingToneUrl());
                }
                // バイブレーション
                if (kidInfoItem.getShockSwitch()) {
                    CommonUtils.stopVibrator(mContext);
                }
            }
        });
        mimamoriPhoneDlg.setOnImadocoSetListener(new MimamoriPhoneDlg.OnImadocoSetListener() {
            @Override
            public void onOperateSet(String pMacId) {
                mimamoriPhoneDlg.dismiss();
                Uri uri = Uri.parse("https://imadoco.smt.docomo.ne.jp/location/top_sp");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                mContext.startActivity(intent);
            }
        });

        // 最初の
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null != bluetoothAdapter && !bluetoothAdapter.isEnabled()) {
            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(
                    mContext,
                    R.style.commonDlg,
                    MessageFormat.format(MessageConstants.MSG_MIMAMORI_WARN_1, mKidInfoEntity.getKidName()));
            processWarringDlg.show();
            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    processWarringDlg.dismiss();
                }
            });
        }
    }
}
